# coding: utf8
# try something like



from modules.dataTable import *
import os
    


class TableSet(dict):
    def __init__(self,csvdir=None,extension='csv'):
        self.csvfiles = {}
        self.tableset = {}
        self.extension = extension
        if csvdir != None:
            for subdir, dirs, files in os.walk(csvdir):
                for file in files:
                    if file[-4:] == '.' + extension:
                        tname = file[0:-4]
                        
                    #fileparts = file.split('.')
                    #if fileparts[-1] == extension:
                    #    tname = "".join(fileparts[0:-1])
                        #print tname,"---->",csvdir + '/' + file
                        self.csvfiles[tname] = csvdir + "/" + file
    
    def postProcessTable(self,dataTable):
        
        pass
                        
        
    def table(self,tname,readColumns=None):
        if self.tableset.has_key(tname) and readColumns == None:
            rd = self.tableset[tname]
        else:
            if readColumns == None:
                print "Loading:",tname
            else:
                print "Loading:",tname,"Columns:",readColumns

            rd = DataTable()
            if self.extension == 'csv':
                rd.readCSV(csvfile=self.csvfiles[tname])
            else:
                if self.extension == 'txt':
                    rd.readTabSeparatedFile(tsvfile=self.csvfiles[tname],readColumns=readColumns)
                        #print self.tableset[tname]
            self.postProcessTable(rd)

            if readColumns == None:
                self.tableset[tname] = rd #cache the whole table
            
        return rd
